<!--
 * @Author: 路程
 * @LastEditTime: 2022-08-13 17:02:21
 * @LastEditors: huangbc
 * @Description: 角色管理
-->
<template>
  <div class="department-container" v-loading.fullscreen.lock="roleLoading">
    <div class="guide-model-box" v-if="nowGuideStep < 4"></div>
    <!-- start 主要内容 -->
    <div class="department-main">
      <div
        v-show="!collapse"
        class="department-left department-state"
      >
        <!-- 新建角色按钮 -->
        <div
          class="dept-search"
          :class="{
            'dept-search-border':
              (tenantType == 0 && hasStaffAuth) ||
              tenantType == 2 ||
              tenantType == 3
          }"
        >
          <el-button v-if="roleCreate" type="primary" @click="createRole()">
            <i class="iconfont icon-add2" style="margin-right:6px"></i>{{ $t('common.button.createRole') }}
          </el-button>
        </div>

        <!-- start 左侧角色树 -->
        <div class="el-tabs__content">
          <div class="department-main-left">
            <div class="department-tree-view">
              <div class="bc-dept" v-if="depts.length > 0">
                <base-tree-dept
                  all-expand
                  :data="depts"
                  :selected="[selectedRole]"
                  :show-checkbox="allowCheckDept"
                  @node-selected="chooseRole"
                  @node-check="chooseDept"
                  :node-render="nodeRender"
                />
              </div>
            </div>
          </div>
        </div>
        <!-- end 左侧角色树 -->
        
        <!-- start 已删除账号 -->
        <div
          class="department-child-item dept-role-item dept-del-role-item"
          :class="{
            'department-role-selected': selectedRole.id == -1,
            'dept-del-role-item-expand': !collapse
          }"
          @click="chooseDelRole()"
        >
          <span>{{ $t('common.account.deletedAccount') }}</span>
          <i class="iconfont icon-arrowright"></i>
        </div>
        <!-- end 已删除账号 -->
      </div>

      <!-- 角色树伸缩按钮 -->
      <div class="collapse">
        <div @click="btnCollapse('left')" v-show="collapseLeft" class="base-collapse-btn-left">
          <i class="iconfont icon-mianbanjiantou"></i>
        </div>
        <div @click="btnCollapse('rigth')" v-show="collapseRight" class="base-collapse-btn-right">
          <i class="iconfont icon-mianbanjiantou"></i>
        </div>
      </div>

      <!-- start 右侧已删除账号列表 -->
      <div
        v-if="activeName === 'role' && selectedRole.id == '-1'"
        class="department-main-right department-main-right_bgFFF"
        v-loading.fullscreen.lock="roleLoading"
      >
        <!-- start 角色人员 -->
        <div class="department-user-block margin-top-0">
          <div class="dept-search-group">
            <el-input
              v-model="roleKeyword"
              :placeholder="$t('common.placeholder.inputStaffNameSearch')"
              style="width: 200px"
              @input="searchRole"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </div>

          <div class="department-user-table">
            <el-table
              v-table-style
              :data="rolePage.list"
              stripe
              @select="roleSelectionHandle"
              @select-all="roleSelectionHandle"
              :highlight-current-row="false"
              show-overflow-tooltip
              header-row-class-name="team-detail-table-header"
              ref="roleMultipleTable"
              :height="delTableContainerHeight"
              class="team-table bbx-normal-list-box"
            >
              <template slot="empty">
                <div v-show="!roleLoading" class="no-data-block">
                  <img class="service-no-icon" :src="salespersonImage" />{{ $t('comomn.base.tip.noStaff') }}
                </div>
              </template>
              <el-table-column prop="displayName" label="姓名" width="180px">
                <div style="display: flex" slot-scope="scope">
                  <a
                    href="javascript:;"
                    @click="goUserDetail(scope.row.userId)"
                    class="view-detail-btn"
                  >
                    <template v-if="isOpenData">
                      <open-data type="userName" :openid="scope.row.staffId"></open-data>
                    </template>
                    <template v-else>{{ scope.row.displayName }}</template>
                  </a>
                  <span v-if="scope.row.isTeamLeader" class="super-admin-label">{{ $t('common.label.leader') }}</span>
                  <span v-if="scope.row.superAdmin == 2" class="super-admin-label">{{ $t('common.label.admin') }}</span>
                  <div
                    style="display: flex"
                    v-if="scope.row.labelList && scope.row.labelList.length"
                  >
                    <span
                      v-for="item in scope.row.labelList"
                      :key="item.id"
                      class="super-admin-label super-admin-label-auto"
                    >{{ item.labelName }}</span>
                  </div>
                </div>
              </el-table-column>
              <el-table-column prop="loginName" :label="$t('common.label.accountNumber')" v-if="tenantType == 1" />
              <el-table-column :label="$t('common.label.deleteTime')" width="180px">
                <template slot-scope="scope">
                  {{
                    scope.row.deleteTime | fmt_datetime
                  }}
                </template>
              </el-table-column>
              <el-table-column :label="$t('comomn.label.unfinishEvent')" width="120px" v-if="!isBasicEditionHideEvent">
                <template v-if="scope.row.eventCount" slot-scope="scope">
                  <a
                    href
                    class="text-center"
                    @click.stop.prevent="
                      createTransTab('event', scope.row.userId)
                    "
                  >{{ scope.row.eventCount }}</a>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.label.unfinishTask')" width="120px">
                <template v-if="scope.row.taskCount" slot-scope="scope">
                  <a
                    href
                    class="text-center"
                    @click.stop.prevent="
                      createTransTab('task', scope.row.userId)
                    "
                  >{{ scope.row.taskCount }}</a>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.label.responsibleCustomerCount')" width="120px">
                <template v-if="scope.row.customerCount" slot-scope="scope">
                  <a
                    href
                    class="text-center"
                    @click.stop.prevent="
                      createTransTab('customer', scope.row.userId)
                    "
                  >{{ scope.row.customerCount }}</a>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.label.personalSparePartStore')" width="120px" v-if="!isBasicEditionHidePart">
                <template v-if="scope.row.spareCount" slot-scope="scope">
                  <a
                    href
                    class="text-center"
                    @click.stop.prevent="
                      createTransTab('stock', scope.row.userId)
                    "
                  >{{ scope.row.spareCount }}</a>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.label.approveCount')" width="120px">
                <template v-if="scope.row.unApproveCount" slot-scope="scope">
                  <a
                    href
                    class="text-center"
                    @click.stop.prevent="
                      createTransTab('approve', scope.row.userId)
                    "
                  >{{ scope.row.unApproveCount }}</a>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.label.deleteReason')" width="180px">
                <template slot-scope="scope">
                  <template v-if="scope.row.show">
                    {{ $t('role.deleteReason[0]') }}
                  </template>
                  <template v-else>
                    {{ $t('role.deleteReason[1]') }}
                  </template>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.label.operate')" width="120px" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.row.show"
                    type="text"
                    @click="resume(scope.row.userId)"
                  >
                    {{ $t('common.base.revert') }}
                  </el-button>
                  <el-popover
                    v-else
                    placement="top-start"
                    width="200"
                    trigger="hover">
                    {{ $t('role.tooltip1') }}
                    <el-button
                      slot="reference"
                      type="text"
                      class="disable-text"
                    >
                      {{ $t('common.base.revert') }}
                    </el-button>
                  </el-popover>
                  <el-button
                    v-if="scope.row.eventCount ||
                      scope.row.taskCount ||
                      scope.row.customerCount ||
                    scope.row.spareCount"
                    type="text"
                    class="transfer-btn"
                    @click="createTransTab('event', scope.row.userId)"
                  >{{ $t('common.button.toHandOver') }}
                  </el-button>
                  <el-popover
                    v-else
                    placement="top-start"
                    width="150"
                    class="disable-popover"
                    trigger="hover">
                    {{ $t('common.base.tip.nothingToHandOver') }}
                    <el-button
                      slot="reference"
                      type="text"
                      class="disable-text"
                    >
                    {{ $t('common.button.toHandOver') }}
                    </el-button>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>

            <div class="table-footer bbx-normal-table-footer">
              <div class="list-info">
                <i18n path="common.base.table.totalCount">
                  {{ rolePage.total }}
                </i18n>
                <template v-if="roleMultipleSelection && roleMultipleSelection.length > 0">
                  <i18n path="common.base.table.selectedNth">
                    <span class="selectedCount"> {{ roleMultipleSelection.length }} </span>
                  </i18n>
                </template>
              </div>
              <el-pagination
                class="customer-table-pagination"
                :pager-count="tenantType==0?5:7"
                background
                @current-change="roleJump"
                @size-change="roleHandleSizeChange"
                :page-sizes="defaultTableData.defaultPageSizes"
                :page-size="roleParams.pageSize"
                :current-page="roleParams.pageNum"
                layout="prev, pager, next, sizes, jumper"
                :total="rolePage.total"
              ></el-pagination>
            </div>
          </div>

          
        </div>
        <!-- end 角色人员 -->
      </div>
      <!-- end 右侧已删除账号列表 -->

      <!-- start 右侧对应角色 人员列表 -->
      <div v-else class="department-main-right department-main-right_bgFFF">
        <!-- start 角色列表 header -->
        <div ref="tableHeaderContainer" class="department-detail-header mar-b-10">
          <div class="department-detail-header-title department-detail-header-title-box">
            <a
              v-if="selectedRole.isSystem !== null && selectedRole.id && roleEdit"
              :href="`${$resourcePrefix}/security/role/view/${selectedRole.id}`"
              :data-id="selectedRole.id"
              @click="goRoleDetail"
              :style="{ color: getThemeColor }"
            >
              <span>{{ selectedRole.name }}</span>
            </a>
            <span v-else>{{ selectedRole.name }}</span>
            <div>
              <el-button
                type="plain-third"
                v-if="roleEdit && selectedRole.id && selectedRole.id != 1 && selectedRole.isSystem !== null"
                style="margin-left:10px;"
                @click="editRole(selectedRole.id)"
              >
                <i class="iconfont icon-edit-square"></i>{{ $t('role.editRolePermission') }}
              </el-button>
              <el-button
                type="plain-third"
                v-if="roleEdit && selectedRole.isSystem === 1 && selectedRole.state === 1"
                style="margin-left:10px;"
                @click="resetRole"
              >{{ $t('role.resetPermission') }}</el-button>
              <el-button
                type="plain-third"
                v-if="roleDelete && selectedRole.isSystem == 0"
                style="margin-left:10px;"
                @click="delRole(selectedRole.id)"
              >
                <i class="iconfont icon-delete"></i>{{ $t('role.deleteRole') }}
              </el-button>
            </div>
          </div>

          <el-row class="dept-info" v-if="selectedRole.type =='parentTag'">
            <el-col :span="6" class="form-view-row">
              <span style="color:#595959">{{ $t('role.accountCountstatistic.buy') }}</span>
              <br />
              <span class="count">{{ accountNum }}</span>
            </el-col>
            <el-col :span="6" class="form-view-row">
              <span style="color:#595959">{{ $t('role.accountCountstatistic.allocated') }}</span>
              <br />
              <span class="count">{{ userCount }}</span>
            </el-col>
            <el-col :span="6" class="form-view-row">
              <span style="color:#595959">{{ $t('role.accountCountstatistic.distributable') }}</span>
              <br />
              <span class="count">{{ surplusNum }}</span>
            </el-col>
          </el-row>
        </div>
        <!-- end 角色列表 header -->
        
        <!-- start 角色列表 人员 -->
        <div class="department-user-block">
          <div ref="tableDoContainer" class="dept-search-group">
            <div class="dept-search-group-left">
              <el-input
                v-model="roleKeyword"
                placeholder="请输入成员信息搜索"
                style="width: 200px;margin-right:12px"
                @change="chooseRole(selectedRole)"
              >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
              <!-- 高级搜索 -->
              <div class="advanced-search-btn pointer" @click.self.stop="panelSearchAdvancedToggle">
                <i class="iconfont icon-filter"></i>
                高级搜索
              </div>
              <el-button v-if="hasStaffAuth && isAuthStaff" type="primary" @click="setRole">分配角色</el-button>
              <el-button
                v-if="isAuthStaff && selectedRole.type == 'toBeAssigned' && tenantType == 0"
                type="primary"
                @click="defaultRoleDialogVisible = true"
              >默认分配角色</el-button>
              <el-button
                v-if="roleCreate && isCustomeRole && isAuthStaff"
                type="primary"
                @click="chooseUser('role')"
              >添加成员</el-button>
              <el-button
                type="plain-third"
                v-if="roleDelete && isCustomeRole && rolePage.list.length && isAuthStaff"
                @click="roleDeleteConfirm()"
              >移除成员</el-button>
            </div>
            <el-dropdown trigger="click">
              <span class="el-dropdown-link"
              >更多操作 <i class="iconfont icon-caidanjiantou-zhankai"></i
              ></span>
              <el-dropdown-menu slot="dropdown">
                    
                <el-dropdown-item v-if="isButtonDisplayed">
                  <div @click="exportAccount()">导出账号</div>
                </el-dropdown-item>
                    
                <el-dropdown-item v-if="isButtonDisplayed">
                  <div @click="exportAccount('all')">导出全部</div>
                </el-dropdown-item>
                    
                <el-dropdown-item v-if="isButtonDisplayed">
                  <div @click="exportFeed()">导出选中动态</div>
                </el-dropdown-item>
                    
                <!-- <el-dropdown-item v-if="isButtonDisplayed"> 
                  <div @click="exportFeed('all')">导出全部动态</div>
                </el-dropdown-item> -->
                <el-dropdown-item v-if="isButtonDisplayed&&roleDelete && isCustomeRole && rolePage.list.length && isAuthStaff"> 
                  <div @click="roleDeleteConfirm()">批量删除</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="isButtonDisplayed"> 
                  <div @click="actionMany('enable')">批量启用</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="isButtonDisplayed"> 
                  <div @click="actionMany('unable')">批量停用</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>

          <div class="department-user-table" >
            <el-table
              border
              :data="rolePage.list"
              stripe
              @select="selectionHandle"
              @select-all="selectionHandle"
              @header-dragend="headerDragend"
              :highlight-current-row="false"
              :height="tableContainerHeight"
              header-row-class-name="team-detail-table-header"
              ref="multipleTable"
              class="team-table bbx-normal-list-box"
            >
              <template slot="empty">
                <div class="no-data-block" v-show="!roleLoading">
                  <img class="service-no-icon" :src="salespersonImage" />
                  当前暂无成员
                  <span
                    v-if="allowAddUser"
                    class="active-btn"
                    @click="chooseUser('role')"
                  >添加成员</span>
                </div>
              </template>
              <el-table-column
                type="selection"
                width="48"
                align="center"
                class-name="select-column"
              ></el-table-column>

              <el-table-column
                prop="displayName"
                label="姓名"
                show-overflow-tooltip
                :width="tableListForWidthStash.displayName.width"
              >
                <div slot-scope="scope">
                  <div style="display: flex">
                    <a
                      href="javascript:;"
                      @click="goUserDetail(scope.row.userId)"
                      class="view-detail-btn view-user-detail-btn"
                    >
                      <template v-if="isOpenData">
                        <open-data type="userName" :openid="scope.row.staffId"></open-data>
                      </template>
                      <template v-else>{{ scope.row.displayName }}</template>
                    </a>
                    <span v-if="scope.row.isTeamLeader" class="super-admin-label">主管</span>
                    <span v-if="scope.row.superAdmin == 2" class="super-admin-label">主管理员</span>
                    <div
                      style="display: flex"
                      v-if="scope.row.labelList&&scope.row.labelList.length"
                    >
                      <span
                        v-for="item in scope.row.labelList"
                        :key="item.id"
                        class="super-admin-label super-admin-label-auto"
                      >{{item.labelName}}</span>
                    </div>
                  </div>
                </div>
              </el-table-column>
              <el-table-column
                prop="loginName"
                :width="tableListForWidthStash.loginName.width"
                label="账号"
                show-overflow-tooltip
              />

              <el-table-column
                prop="roleDepartment"
                label="所属部门"
                :width="tableListForWidthStash.roleDepartment.width"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  {{ scope.row.roles && scope.row.tagList.map(i => (i && i.tagName) || '').join('，') }}
                </template>
              </el-table-column>

              <el-table-column
                prop="role"
                label="角色"
                :width="tableListForWidthStash.role.width"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  {{ scope.row.roles && scope.row.roles.map(i => (i && i.name) || '').join('，') }}
                </template>
              </el-table-column>

              <el-table-column
                prop="cellPhone"
                :width="tableListForWidthStash.cellPhone.width"
                label="电话"
                show-overflow-tooltip
              />
              <el-table-column
                prop="wechat"
                label="微信"
                :width="tableListForWidthStash.wechat.width"
                show-overflow-tooltip
              />
              <el-table-column
                prop="email"
                label="邮箱"
                :width="tableListForWidthStash.email.width"
                show-overflow-tooltip
              />
              <el-table-column
                prop="enabled"
                :width="tableListForWidthStash.enabled.width"
                label="状态"
              >
                <template slot-scope="scope">
                  {{ scope.row.enabled == 1 ? '启用' : '停用' }}
                </template>
              </el-table-column>
              <el-table-column prop="enabled" :width="tableListForWidthStash.createTime.width" label="创建时间">
                <template slot-scope="scope">{{
                  scope.row.createTime | fmt_datetime
                }}</template>
              </el-table-column>
              <template v-if="tenantType == 1 && isAuthStaff">
                <el-table-column
                  prop="workArea"
                  label="操作"
                  :width="tableListForWidthStash.workArea.width"
                  fixed="right"
                >
                  <template slot-scope="scope">
                    <el-button
                      :disabled="scope.row.pending"
                      type="text"
                      @click="openCreateUserPanel(scope.row)"
                    >编辑</el-button>
                    <el-button
                      :disabled="scope.row.pending"
                      v-if="scope.row.enabled == 1"
                      type="text"
                      style="color: #e6a23c"
                      @click="toggleEnable(scope.row)"
                    >停用</el-button>
                    <el-button
                      :disabled="scope.row.pending"
                      v-else
                      type="text"
                      @click="toggleEnable(scope.row)"
                    >启用</el-button>
                    <el-button
                      :disabled="scope.row.pending"
                      type="text"
                      style="color: #fb602c"
                      @click="deleteDeptUser(scope.row)"
                    >删除</el-button>
                    <el-button type="text" @click="userResetPwdConfirm(scope.row.userId)">重置密码</el-button>
                  </template>
                </el-table-column>
              </template>
              <template v-if="tenantType != 1">
                <!-- 钉钉端操作按钮 -->
                <el-table-column
                  prop="workArea"
                  label="操作"
                  :width="tableListForWidthStash.workArea.width"
                  fixed="right"
                >
                  <template slot-scope="scope">
                    <el-button
                      :disabled="scope.row.pending"
                      type="text"
                      @click="openCreateUserPanel(scope.row)"
                    >编辑</el-button>
                    <el-button
                      :disabled="scope.row.pending"
                      v-if="scope.row.enabled == 1"
                      type="text"
                      style="color: #e6a23c"
                      @click="toggleEnable(scope.row)"
                    >停用</el-button>
                    <el-button
                      :disabled="scope.row.pending"
                      v-else
                      type="text"
                      @click="toggleEnable(scope.row)"
                    >启用</el-button>
                    <el-button
                      :disabled="scope.row.pending"
                      type="text"
                      style="color: #fb602c"
                      @click="deleteDeptUser(scope.row)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </template>
            </el-table>

            <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer">
              <div class="list-info">
                共 <span class="level-padding">{{ rolePage.total }}</span>记录
              </div>
              <el-pagination
                class="customer-table-pagination"
                :pager-count="tenantType==0?5:7"
                background
                @current-change="roleJump"
                @size-change="roleHandleSizeChange"
                :page-sizes="defaultTableData.defaultPageSizes"
                :page-size="roleParams.pageSize"
                :current-page="roleParams.pageNum"
                layout="prev, pager, next, sizes, jumper"
                :total="rolePage.total"
              ></el-pagination>
            </div>
          </div>

          
        </div>
        <!-- end 角色列表 人员 -->
      </div>
      <!-- end 右侧对应角色 人员列表 -->
    </div>
    <!-- end 主要内容 -->
    
    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleDialogVisible"
      width="35%"
      @close="roleDialogClosed"
    >
      <el-form label-position="top" :model="addUserForm" ref="roleFormRef" v-if="roleDialogVisible">
        <el-select
          v-model="addUserForm.roleIdList"
          placeholder="请选择角色"
          style="width:100%;"
          multiple
        >
          <el-option
            v-for="item in addUserForm.RoleList"
            :label="item.name"
            :value="item.id"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :disabled="pending"
          :loading="pending"
          @click="dispatchRole"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 自动分配角色的对话框 -->
    <el-dialog
      title="默认分配账号"
      :visible.sync="defaultRoleDialogVisible"
      width="35%"
      @close="defaultRoleClosed"
    >
      <el-form label-position="top" :model="roleForm" ref="defaultRoleForm">
        <el-form-item label="为新进入的用户选择一个默认角色或由管理员每次指定"></el-form-item>
        <el-select v-model="roleForm.roleId" placeholder="请选择角色" style="width:100%;">
          <el-option
            v-for="item in autoAuthRoles"
            :label="item.text"
            :value="item.id"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="defaultRoleDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :disabled="pending"
          :loading="pending"
          @click="dispatchDefaultRole"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 重置密码的对话框 -->
    <el-dialog
      title="重置密码"
      :visible.sync="resetDialogvisible"
      width="400px"
      @close="resetDialogClosed"
      class="reset-dialog-form-dialog"
    >
      <el-form label-position="top" 
        ref="restFormRef" 
        
        class="reset-dialog-form"
        :rules="changePassWordFormRules"
        :model="resetForm"
      >
        <label>确定将该成员的密码重置吗？</label>
        <el-form-item label="重置后密码：" required prop="pwd">
          <el-input
            placeholder="请输入密码"
            v-model="resetForm.pwd"
            type="password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="resetDialogClosed">取 消</el-button>
        <el-button
          type="primary"
          :disabled="pending"
          :loading="pending"
          @click="resetUserPwd"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- start 新建人员弹窗 -->
    <base-modal
      :show.sync="userDialogVisible"
      class="add-dialog-container service_body"
      width="720px"
      @closed="userDialogVisible = false"
      title="修改账号"
    >
      <create-user-panel
        style="padding-top:10px"
        ref="createUserPanel"
        :submit="userAdd"
        :user-row="userRow"
        key-from="role"
      ></create-user-panel>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="userDialogSubmit">确 定</el-button>
      </span>
    </base-modal>

    <!-- 高级搜索弹窗 -->
    <base-search-drawer
      :show.sync="visible"
      :storage-key="advancedColumnNumStorageKey"
      @reset="resetParams"
      @search="initializeDept(false)"
      @changeWidth="setAdvanceSearchColumn"
      @getColumnNum="setAdvanceSearchColumn"
    >
      <base-search-panel ref="searchPanel" :column-num="columnNum" :fields="fields"></base-search-panel>
    </base-search-drawer>

    <!-- 导出动态的对话框 -->
    <el-dialog
      title="导出动态"
      :visible.sync="exportDialogvisible"
      width="600px"
      @close="exportDialogClosed"
    >
      <el-form label-position="top" ref="exportFormRef" >
        <el-form-item label="[可选]选择时间">
          <el-date-picker
            v-model="selectdatetime"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            :default-time="['00:00:00', '23:59:59']"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="动态类型" >
          <el-checkbox v-model="checkedAllTypes">工作状态</el-checkbox>
          <el-checkbox-group v-model="activeTypes" :disabled="checkedAllTypes">
            <el-checkbox :label="item.value" v-for="item in dynamicTypes" :key="item.value">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="exportDialogClosed">取 消</el-button>
        <el-button
          type="primary"
          :disabled="pending"
          :loading="pending"
          @click="exportData"
        >{{ pending ? '正在导出' : '导出' }}</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
/* api */
import * as serviceProviderApi from '@src/api/serviceProviderApi';
import { getDelUser, getBaseLabelList } from '@src/api/DepartmentApi';
import * as RoleApi from '@src/api/RoleApi';
import md5 from 'js-md5';
import * as TeamApi from '@src/api/TeamApi';

import { getAdvancedFields } from './fields';
import { safeNewDate } from '@src/util/time';
/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum.ts'

// const
import { RoleType, TagType } from '@src/modules/dept/AdvancedType.ts';


import { checkButtonDisplayed } from '@src/util/dom';

/* components */
import CreateUserPanel from '@src/modules/dept/component/CreateUserPanel.vue';
import {
  isBasicEditionControl,
  isBasicEditionHideEvent,
  isBasicEditionHidePart,
} from '@shb-lib/version';
import TeamEditView from '@src/modules/serviceProvider/component/CreateTeamPanel.vue';
import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';

/* utils */
import _ from 'lodash';
import http from '@src/util/http';
import Page from '@model/Page';
import Platform, { isOpenData, openAccurateTab } from '@src/util/platform.ts';
import tourGuide from '@src/mixins/tourGuide';
import { formatDate, objectToUrlParams } from 'pub-bbx-utils';
import { storageGet, storageSet } from '@src/util/storageV2.js';


import { ValidatePassWordReg } from '@src/model/const/Reg'
import { PASS_WORD_MESSAGE } from '@src/model/const/Alert'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { defaultTableData } from '@src/util/table'
const pageSizeStorageKey = 'dept_role_list_pageSize';
let export_state;

let validatePass = (rule, value, callback) => {
  
  if (!value) {
    callback(new Error('请输入密码'));
  } else {
    
    if (value) {
      if (ValidatePassWordReg.test(value)) {
        callback();
      } else {
        callback(new Error(PASS_WORD_MESSAGE));
      }
    }
    
    callback();
  }
};
import { getOssUrl } from '@src/util/assets'
const salespersonImage = getOssUrl('/salesperson.png')
export default {
  name: 'department-view',
  inject: ['initData'],
  mixins: [tourGuide],
  data() {
    return {
      defaultTableData,
      salespersonImage,
      isButtonDisplayed: checkButtonDisplayed(),
      isOpenData,
      userDialogVisible: false,
      nowGuideStep: 5,
      collapse: false,
      collapseLeft: true,
      collapseRight: false,
      deptKeyword: '',
      activeName: 'role',
      activeName1: 'user',
      roles: [],
      selectedRole: {},
      keyword: '',

      autoAuthRoles: [],
      roleKeyword: '',
      roleLoading: false,
      roleDialogVisible: false,
      pending: false,
      roleMultipleSelection: [],
      roleParams: {},
      resetDialogvisible: false,
      resetForm: {
        userId: '',
        pwd: '',
      },

      deptInfo: {},
      userRow: '',
      allowCheckDept: false,
      depts: [],
      isSeeAllOrg: false, // 是否开始降低组织架构人员可见性开关
      loading: false,
      multipleSelection: [],
      params: {},
      rolePage: new Page(), // 用户列表
      userPage: new Page(), // 用户列表
      totalCount: 0,
      userCount: 0, // 已开通账号数量
      accountNum: 0, // 账号总数量
      surplusNum: 0, // 剩余
      addUserForm: {
        userIdList: [],
        roleIdList: [],
        RoleList: [],
      },
      visible: false,
      columnNum: 1,
      advancedColumnNumStorageKey: StorageKeyEnum.RoleListAdvancedColumnNum,
      rolesList: [],
      baseLaberlList: [],
      defaultRoleDialogVisible: false,
      roleForm: {
        roleId: '0',
      },
      // 存储列表宽度缓存
      tableListForWidthStash: {
        displayName: { width: '180px' },
        loginName: {width:'120px'},
        roleDepartment: { width: '120px' },
        role: {width:'120px'},
        cellPhone: {width:'120px'},
        wechat: {width:'120px'},
        email: {width:'120px'},
        enabled: {width:'120px'},
        workArea: { width: '220px' },
        createTime:{width:'160px'}
      },
      // 列表缓存标识
      tableStashKey: 'departmentRoleList',
      
      // 导出动态
      exportDialogvisible: false,
      selectdatetime: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近半年',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
              const end = safeNewDate();
              const start = safeNewDate();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 360);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
      dynamicTypes:[
        {value:0, name:'工单备注'},
        {value:1, name:'工单日志'},
        {value:2, name:'工单位置'}      
      ],
      activeTypes:[],
      checkedAllTypes: true,
      changePassWordFormRules: {
        pwd: [
          {
            required: true,
            validator: validatePass,
            trigger: ['blur', 'change']
          },
          { min: 8, message: '最小长度需为 8 位', trigger: 'blur' }
        ],
      },
      tableContainerHeight:'440px',
      delTableContainerHeight:'440px',
    };
  },
  computed: {
    isCustomeRole() {
      // 自定义角色id
      return !this.selectedRole.type;
    },
    corpId() {
      return this.initData.corpId || '';
    },
    // 0：钉钉端，1：自建，2：企微端
    tenantType() {
      return this.initData.tenantType;
    },
    authorities() {
      return this.initData.authorities || {};
    },
    allowAddUser() {
      return (
        this.authorities.AUTH_STAFF == 3
        && this.authorities.AUTH_ROLE == 3
        && this.authorities.AUTH_TAG == 3
      );
    },
    // 查看组织架构权限对应之前的团队权限
    hasTagAuth() {
      // 多端默认true
      if (this.tenantType == 1) return true;
      return 'AUTH_TAG' in this.authorities;
    },
    // 账号权限
    hasStaffAuth() {
      // 多端默认true
      if (this.selectedRole.type == 'toBeAssigned') return true;
    },
    // 角色权限
    hasRoleAuth() {
      // 多端默认true
      if (this.tenantType == 1) return true;
      return 'AUTH_ROLE' in this.authorities;
    },
    // 新增角色
    roleCreate() {
      // if (this.tenantType == 1) return true;
      return 'ROLE_CREATE' in this.authorities;
    },
    // 删除角色
    roleDelete() {
      return 'ROLE_DELETE' in this.authorities;
    },
    // 编辑角色
    roleEdit() {
      return 'ROLE_EDIT' in this.authorities;
    },
    // 查看角色
    roleView() {
      // if (this.tenantType == 1) return true;
      return 'ROLE_VIEW' in this.authorities;
    },
    // 是否账号管理权限
    isAuthStaff() {
      return 'AUTH_STAFF' in this.authorities;
    },
    // 是否在钉钉环境
    isDingTalk() {
      return Platform.isDingTalk();
    },
    isBasicEditionControl() {
      return isBasicEditionControl();
    },
    // 基础版隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent();
    },
    // 基础版隐藏备件
    isBasicEditionHidePart() {
      return isBasicEditionHidePart();
    },
    dept_role_data() {
      let roles = this.initData.rolesJson;
      if (this.isBasicEditionControl && roles) {
        roles.forEach((item) => {
          let descStr = item?.desc || '';
          // 基础版普通管理员过滤信息管理
          if (item.id === '2') {
            const flag = descStr.endsWith('等');
            if (flag) {
              descStr = descStr.substring(0, descStr.length - 1);
            }
            let descArr = descStr.split('、');
            descArr = descArr.filter((subItem) => subItem !== '信息管理');
            item.desc = flag ? `${descArr.join('、')}等` : descArr.join('、');
          }
          // 基础版服务总监过滤信息管理、备件管理、费用管理
          if (item.id === '5') {
            const flag = descStr.endsWith('等');
            if (flag) {
              descStr = descStr.substring(0, descStr.length - 1);
            }
            let descArr = descStr.split('、');
            descArr = descArr.filter(
              (subItem) =>
                subItem !== '信息管理'
                && subItem !== '备件管理'
                && subItem !== '费用管理'
            );
            item.desc = flag ? `${descArr.join('、')}等` : descArr.join('、');
          }
        });
      }

      return roles || [];
    },
    // 高级搜索是否展示角色
    isSearchRole() {
      if (this.selectedRole.type == 'assigned' || this.selectedRole.type == 'parentTag')
        return true;
    },
    // 高级搜索字段
    fields() {
      let f = {};
      return getAdvancedFields(this)
        .map(field => {
          f = _.cloneDeep(field);
          let formType = f.formType;

          if (f.displayName === '所属部门') {
            formType = 'tags';
          }

          return Object.freeze({
            ...f,
            isNull: 1,
            formType,
            originalFormType: f.formType,
          })
        })
        .sort((a, b) => a.orderId - b.orderId)
        .filter(x => !this.isSearchRole ? x.fieldName !== 'roleIds' : x);
    },
  },
  watch:{
    checkedAllTypes(newVal){
      if(newVal)this.activeTypes = []
    }
  },
  created() {
    if (this.hasStaffAuth || this.hasRoleAuth) {
      if (!this.hasTagAuth) {
        this.activeName = 'role';
        this.chooseRole(this.selectedRole);
      }
    }
    // 自动分配角色
    this.autoAuthRoles = [{ id: '0', text: '由管理员每次指定' }].concat(
      this.dept_role_data
    );
    
    this.buildColumn();
    // 读取列表的分页缓存数据
    let pageSizeStash = storageGet(pageSizeStorageKey) || '';
    pageSizeStash = pageSizeStash ? JSON.parse(pageSizeStash) : {};
    if (pageSizeStash.hasOwnProperty(this.activeName1)) {
      this.roleParams.pageSize = pageSizeStash[this.activeName1];
    }
    
    this.initialize();
    this.$eventBus.$on('submit', this.userAdd);
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
  },  
  methods: {
    // 移除成员按钮
    async roleDeleteConfirm() {
      if (this.multipleSelection.length <= 0) {
        return this.$platform.alert('请先选择需要移除的成员');
      }
      const hasSuperAdmin = this.multipleSelection.some((user) => {
        return user.superAdmin == 2;
      });
      if (hasSuperAdmin) {
        return this.$platform.alert('移除失败！主管理员不允许移除系统管理员角色');
      }
      if (await this.$platform.confirm('确定要把选中成员从该角色中移除吗？')) {
        this.roleUserDelete();
      }
    },

    // 角色批量移除成员
    roleUserDelete() {
      const params = {
        userIdList: this.multipleSelection.map((item) => item.userId).join(','),
        roleId: this.selectedRole.id,
      };
      this.loading = true;

      RoleApi.roleDeleteUser(params)
        .then((result) => {
          const isSucc = result.status == 0;
          if (isSucc) {
            this.initialize(true);
          }
          this.multipleSelection = [];
          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '移除成功' : result.message,
            type: isSucc ? 'success' : 'error',
          });
        })
        .catch((err) => console.log(err))
        .finally(() => (this.loading = false));
    },
    
    /** 
     * @deprecated 已废弃
    */
    /**
     * @description: // 选择成员 打开成员弹窗组件
     * @param {String} type 默认有role/dept？ 本页面只会是role
     */    
    chooseUser(type) {
      const options = {
        title: '请选择成员',
        seeAllOrg: true,
        max: -1,
        selectedUser: this.userPage.list,
        mountEl: this.$el,
        showNoRole: true
      };

      this.$fast.contact
        .choose('team', options)
        .then((result) => {
          if (result.status == 0) {
            const users = result?.data?.users || [];
            if (type === 'role') this.addRoleUserList(users);
          }
        })
        .catch((err) => console.error(err));
    },

    /**
     * @description: 角色批量增加用户
     * @param {Object} users 选人组件选中的用户
     */    
    addRoleUserList(users) {
      const params = {
        roleId: this.selectedRole.id,
        userIdList: users.map((item) => item.userId).join(',')
      };
      this.loading = true;

      RoleApi.roleAddUser(params)
        .then((result) => {
          const isSucc = result.status == 0;
          if (isSucc) this.initialize(false) // 刷新列表

          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '添加成功' : result.message,
            type: isSucc ? 'success' : 'error',
          });
        })
        .catch((err) => console.log(err))
        .finally(() => (this.loading = false));
    },

    /**
     * @description: 编辑角色权限按钮
     * @param {Number} id 选中的角色id
     */    
    editRole(id) {
      const fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: 'edit_role',
      //   title: '编辑角色',
      //   close: true,
      //   url: `/security/role/edit/${id}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEditRole,
        key: id,
        fromId
      })
    },

    /**
     * @description: 删除角色按钮
     * @param {Number} id 选中的角色id
     */    
    async delRole(id) {
      try {
        if (await this.$platform.confirm('确定要删除该角色权限吗？')) {
          const { status, message } = await RoleApi.roleDelete({id})
          const isSucc = status == 0;
          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '角色权限删除成功' : message,
            type: isSucc ? 'success' : 'error',
          });
          if (isSucc) this.initialize(true); // 角色删除成功后需要刷新角色列表
        }
      } catch (error) {
        console.error(error);
      }
    },

    // 重置权限按钮
    async resetRole() {
      try {
        if (await this.$platform.confirm('确定要重置该角色权限吗？')) {
          const { status, message } = await RoleApi.roleDelete({id: this.selectedRole.id})
          const isSucc = status == 0;
          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '角色权限重置成功' : message,
            type: isSucc ? 'success' : 'error',
          });
          if (isSucc) {
            this.selectedRole.state = 0 // 成功重置之后，将状态初始化为0，不展示重置权限按钮。
            this.initialize(false);
          }
        }
      } catch (error) {
        console.error(error);
      }
    },

    // 打开角色详情页面
    goRoleDetail(event) {
      event.preventDefault();
      if (!window.frameElement) return;
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `tab_role_view_${this.selectedRole.id}`,
      //   title: '角色详情',
      //   close: true,
      //   reload: true,
      //   url: `/security/role/view/${this.selectedRole.id}?`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.pageSecurityRoleView,
        key: this.selectedRole.id,
        fromId
      })
    },

    /**
     * @description: 新建人员弹窗 submit handler
     * @param {Object} form 组件form data
     */    
    userAdd(form) {
      let params = JSON.parse(JSON.stringify(form));
      params.roles = params.role.map((r) => ({ id: r })) || [];

      this.loading = true;

      RoleApi.userCreateAndAddDepartmentUser(params)
        .then((result) => {
          const isSucc = result.status == 0;

          if (isSucc) {
            this.$refs.createUserPanel.close();
            this.userDialogVisible = false;
            this.initialize(false);
          }

          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '操作成功' : result.message,
            type: isSucc ? 'success' : 'error',
          });
        })
        .catch((err) => console.log(err))
        .finally(() => (this.loading = false));
    },

    // 新建人员弹窗-确定按钮
    userDialogSubmit() {
      this.$refs.createUserPanel.validate();
    },

    // 新建角色按钮
    createRole() {
      const fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: 'create_role',
      //   title: '新建角色',
      //   close: true,
      //   url: '/security/role/create',
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateRole,
        fromId
      })
    },

    /**
     * @description: 伸缩按钮
     * @param {String} dir direction
     */    
    btnCollapse(dir) {
      if (dir === 'left') {
        this.collapse = true;
        this.collapseLeft = !this.collapseLeft;
        this.collapseRight = true;
      } else {
        this.collapse = false;
        this.collapseRight = !this.collapseRight;
        this.collapseLeft = true;
      }
    },

    // 分配角色弹窗 关闭
    roleDialogClosed() {
      this.$refs.roleFormRef.resetFields();
    },

    // 默认分配角色弹窗 关闭
    defaultRoleClosed() {
      this.$refs.defaultRoleForm.resetFields();
    },

    // 分配角色按钮
    setRole() {
      if (this.multipleSelection.length && this.addUserForm.RoleList.length) {
        this.roleDialogVisible = true;
      } else {
        this.$platform.notification({
          title: '提示',
          message: '请选择成员',
          type: 'error',
        });
      }
    },

    // 确定 分配角色
    async dispatchRole() {
      this.multipleSelection.map((r) =>
        this.addUserForm.userIdList.push(r.userId)
      );
      try {
        this.pending = true;
        const { roleIdList = [], userIdList = [] } = this.addUserForm
        const params = {
          roleIdList: roleIdList && roleIdList.join(','),
          userIdList: userIdList && userIdList.join(',')
        }

        const { status, message } = await RoleApi.roleAssignRoles(params);
        this.$platform.notification({
          title: status === 0 ? '分配角色成功' : '分配角色失败',
          message: status === 0 ? '' : message || '',
          type: status === 0 ? 'success' : 'error',
        });
        this.pending = false;
        this.roleDialogVisible = false;
        this.addUserForm.roleIdList = []
        this.addUserForm.userIdList = [];
        this.multipleSelection = [];
        this.initializeDept(false);
      } catch (error) {
        this.pending = false;
        console.error(error);
      }
    },

    // 确定 默认分配角色
    async dispatchDefaultRole() {
      try {
        this.pending = true
        const params = { state: this.roleForm.roleId != 0, roleId: this.roleForm.roleId }
        const { status, message } = await RoleApi.roleAutoAuthSave(params)
        if (status !== 0)
          return this.$platform.notification({
            title: '默认分配权限失败',
            message: message || '',
            type: 'error',
          })
        this.pending = false
        this.defaultRoleDialogVisible = false
        this.defaultRoleClosed()
        this.$platform.notification({
          title: '默认分配权限成功',
          type: 'success',
        })
      } catch (error) {
        this.pending = false
        console.error(error)
      }
    },

    /**
     * @description: table 操作列 停用or启用按钮
     * @param {Object} row table row
     */    
    toggleEnable(row) {
      row.pending = true;
      RoleApi.userEnable({ userId: row.userId }).then((res) => {
        row.pending = false;
        if (res.status) return this.$platform.alert(res.message);
        this.initialize(false);
      })
        .catch((err) => {
          row.pending = false;
          console.error('toggleStatus catch err', err);
        });
    },

    /**
     * @description: table 操作列 删除按钮
     * @param {Object} row table row
     */    
    async deleteDeptUser(row) {
      if (await this.$platform.confirm('确定要把选中成员删除吗？')) {
        row.pending = true;
        RoleApi.userDelete({ userId: row.userId }).then((res) => {
          row.pending = false;
          if (res.status) return this.$platform.alert(res.message);
          this.initialize(false);
        })
          .catch((err) => {
            row.pending = false;
            console.error('toggleStatus catch err', err);
          });
      }
    },
    
    /**
     * @description: table 操作列 重置密码按钮
     * @param {Object} row table row
     */    
    userResetPwdConfirm(userId) {
      this.resetDialogvisible = true;
      this.resetForm.userId = userId;
    },

    // 重置密码弹窗关闭
    resetDialogClosed() {
      this.resetForm.userId = '';
      this.resetForm.pwd = '';
      this.resetDialogvisible = false;
    },

    // 操作-恢复 按钮
    async resume(userId) {
      try {
        if (await this.$platform.confirm('确定要恢复该账号吗？')) {
          const { status, message } = await RoleApi.userResume({ userId });
          const isSucc = status == 0;
          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '账号恢复成功' : message,
            type: isSucc ? 'success' : 'error',
          });
          isSucc && this.chooseRole(this.selectedRole);
        }
      } catch (error) {
        console.error(error);
      }
    },
    
    /**
     * @description: 打开转交详情页面
     * @param {*} type event/task/customer/stock/approve
     * @param {*} userId 用户id
     */    
    createTransTab(type, userId) {
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: 'M_JOBTRANSFER_DETAIL',
      //   title: '转交详情',
      //   close: true,
      //   url: `/jobtransfer/view?type=${type}&userId=${userId}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageJobtransferView,
        params: `type=${type}&userId=${userId}`,
        fromId
      })
    },

    // 重置密码弹窗 确认重置密码
    async resetUserPwd() {
      const isValidate = await this.$refs.restFormRef.validate();
      if (!isValidate) return;

      let params = {};
      params.userId = this.resetForm.userId;
      params.password = md5(this.resetForm.pwd);
      RoleApi.resetPwdUpdateAdmin(params)
        .then((result) => {
          let isSucc = result.status == 0;
          this.$platform.notification({
            title: isSucc ? '成功' : '失败',
            message: isSucc ? '密码重置成功' : result.message,
            type: isSucc ? 'success' : 'error',
          });
          if (isSucc) this.resetDialogClosed();
        })
        .catch((err) => console.log(err));
    },

    // 角色人员搜索
    searchRole() {
      this.rolePage.list = [];
      this.chooseRole(this.selectedRole);
    },

    // 已删除账号点击
    chooseDelRole() {
      this.activeName = 'role';
      this.selectedRole = {};
      this.rolePage.list = [];
      let role = { id: -1, text: '已删除账号' };
      this.chooseRole(role);
    },

    /**
     * @description: 选中角色 获取右侧角色列表等数据
     * @param {Object} role 选中角色数据
     */
    chooseRole(role) {
      this.multipleSelection = [];
      this.roleMultipleSelection = [];
      if (this.selectedRole.id != role.id) {
        this.roleKeyword = '';
      }
      this.selectedRole = role;
      this.roleLoading = true;
      // 获取角色下面的人员
      this.roleParams.keyword = this.roleKeyword;
      this.roleParams.roleId = '';
      this.roleParams.roleType = '';
      this.roleParams.pageNum = 1;
      this.rolePage.list = [];
      if (role.type == 'toBeAssigned') {
        // 待分配账号
        this.roleParams.roleType = 'noauth';
      } else if (role.type == 'assigned') {
        // 已分配
        this.roleParams.roleType = 'haveauth';
      } else if (role.id == -1) {
        // 已删除账号
        this.roleParams.roleType = 'delauth';
      } else {
        this.roleParams.roleId = role.id;
      }
      this.getRoleUserList({
        ...this.roleParams,
        ...this.buildSearchParams()
      })
        .then((rolePage) => {
          this.rolePage.merge(Page.as(rolePage));
          this.$nextTick(()=> {
            this.knowTableContainerHeight()
            let that_ = this;
            window.onresize = _.debounce(()=>{
              that_.knowTableContainerHeight()
            }, 500)
          })
        })
        .catch((err) => console.error('err', err))
        .finally(() => {
          this.roleLoading = false
          this.visible = false
        });
    },

    /**
     * @description: 获取角色成员列表
     * @param {Objet} params 入参
     */    
    async getRoleUserList(params) {
      if (this.selectedRole.id == -1) return getDelUser(params);
      const { status, data } = await RoleApi.userList(params)
      return status === 0 ? data || {} : {};
    },

    // 获取已开通账号等数据
    getBuyAndUseUserNumData() {
      RoleApi.tenantGetBuyAndUseUserNum()
        .then((result) => {
          let data = result.data || {};
          this.totalCount = data.totalCount || 0;
          this.userCount = data.userCount || 0; // 已开通账号数量
          this.accountNum = data.accountNum || 0; // 账号总数量
          this.surplusNum = Number(data.accountNum) - Number(data.userCount) || 0;

          // 试用版展示为 试用
          if (data?.isPay != 1) {
            this.accountNum = '试用';
            this.surplusNum = '试用';
          }
        })
        .catch((err) => console.log(err));
    },

    // 选择服务商 没啥用
    chooseDept(event) {
      let { node, value } = event;
    },

    /** 抓取服务商数据 */
    async fetchDept() {
      let params = {
        seeAllOrg: this.isSeeAllOrg,
        keyword: this.deptKeyword,
      };

      return await serviceProviderApi
        .tree(params)
        .then((result) => {
          return (result && result.data) || [];
        })
        .catch((err) => console.error('err', err));
    },
    
    /* 查询是否开启 降低组织架构的开关 */
    async getSeeAllOrg() {
      return await http.post('/setting/user/getSeeAllOrg').then((result) => {
        return result;
      });
    },

    /* 跳转 用户详情页 */
    goUserDetail(id) {
      if (!window.frameElement) return;

      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `tab_department_view_${id}`,
      //   title: '成员详情',
      //   close: true,
      //   reload: true,
      //   url: `/security/user/view/${id}?from=department`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSecurityUserView,
        key: id,
        params: 'from=department',
        reload: true,
        fromId
      })
    },
    
    // 分页组件size-change handler
    roleHandleSizeChange(pageSize) {
      this.roleParams.pageSize = pageSize;
      this.roleParams.pageNum = 1;
      this.rolePage.list = [];
      this.roleLoading = true;

      let stash_data = storageGet(pageSizeStorageKey) || {};
      storageSet(pageSizeStorageKey, JSON.stringify({
        ...stash_data,
        [this.activeName1]: pageSize
      }))
      return this.getRoleUserList({...this.roleParams, ...this.buildSearchParams()})
        .then((rolePage) => {
          this.rolePage.merge(Page.as(rolePage));
        })
        .catch((err) => console.error('err', err))
        .finally(() => (this.roleLoading = false));
    },

    /** 初始化 */
    initialize(isInit = true) {
      this.initializeDept(isInit);
    },

    /** 初始化服务商数据 */
    async initializeDept(isInit = true) {
      this.roleLoading = true;
      this.isSeeAllOrg = false;

      try {
        /* 如果开启 查询按组织架构选项 */
        let result = await this.getSeeAllOrg();
        this.isSeeAllOrg = result.data;
      } catch (error) {
        console.log('error: ', error);
      }
      this.getBuyAndUseUserNumData(); // 已开通账号数量
      this.depts = [];
      RoleApi.getRoleTree()
        .then((result) => {
          let obj = result.data;
          for (let o of obj.children) o.id = o.type;

          this.depts.push(obj);
          this.addUserForm.RoleList = this.depts[0]?.children[1]?.children || [];
          this.chooseRole(
            isInit ? this.depts[0] : _.cloneDeep(this.selectedRole)
          );
        })
        .catch((err) => console.error(err));
    },

    // 分页组件current-change handler
    roleJump(pageNum) {
      this.roleParams.pageNum = pageNum;
      this.rolePage.list = [];
      this.roleLoading = true;

      return this.getRoleUserList({
        ...this.roleParams,
        ...this.buildSearchParams()
      })
        .then((rolePage) => {
          this.rolePage.merge(Page.as(rolePage));
        })
        .catch((err) => console.error('err', err))
        .finally(() => (this.roleLoading = false));
    },

    // 角色树渲染
    nodeRender(h, node) {
      let content = (
        <span>
          {node.name}（{node.count || 0}）
        </span>
      );
      return content;
    },

    // 编辑成员
    openCreateUserPanel(row) {
      if (row) {
        let obj = JSON.parse(JSON.stringify(row));
        obj.dateTime = safeNewDate().getTime();
        this.userRow = JSON.stringify(obj);
      } else {
        this.userRow = '';
      }
      this.userDialogVisible = true;
    },
    
    /** select dept person */
    selectionHandle(selection) {
      this.multipleSelection = [...this.multipleSelection, ...selection.slice()];
    },

    /** select role person */
    roleSelectionHandle(selection) {
      this.roleMultipleSelection = selection.slice();
    },
    
    // 构建搜索参数
    buildSearchParams() {
      let advancedSearchParams = this.$refs.searchPanel ? this.$refs.searchPanel.buildParams() : {};
      const { tags, roleIds, enabled, labelIds } = advancedSearchParams;
      const tagIdsStr = tags?.map(x => x.id);

      return {
        ...this.params,
        roleIds: roleIds?.filter(x => x !== RoleType),
        tagIds: tagIdsStr?.filter(x => x !== TagType),
        enabled: enabled ? Number(enabled) : '',
        labelIds,
        advancedSearchRoleType: roleIds?.some(x => x === RoleType),
        advancedSearchTagType: tagIdsStr?.some(x => x === TagType)
      }
    },

    // 高级搜索
    panelSearchAdvancedToggle() {
      this.getRoleList();
      this.getBaseLabelList();
      this.visible = true;
    },

    // 设置高级搜索展示列数
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },

    // 重置
    resetParams() {
      window.location.reload()
    },

    // 获取角色列表
    getRoleList() {
      RoleApi.getRoleTree()
        .then(result => {
          if (!result || !result.data || !result.data.children || result.data.children.length < 2)
            return false

          if (result.data.children[1].type === 'assigned') {
            let roles = result.data.children[1].children;
            this.rolesList = roles.map(role => ({ text: role.name, value: role.id }));
            this.rolesList.unshift({ text: '无', value: RoleType })
          }
        })
        .catch((err) => console.error(err));
    },

    // 获取标签数据
    getBaseLabelList() {
      getBaseLabelList().then(res => {
        const { status, data } = res;
        if (status !== 0) return;
        this.baseLaberlList = data.map(x => ({ text: x.tagName, value: x.id }));
      })
    },
    
    // 表单拖拽钩子函数
    headerDragend(newWidth, oldWidth, column, event) {
      let stash_data = storageGet('notStandardTableStash') || '';
      stash_data = (stash_data && JSON.parse(stash_data)) || {};
      this.$set(this.tableListForWidthStash, column.property, { width: `${column.width}px` });
      stash_data[`${this.tableStashKey}`] = this.tableListForWidthStash

      storageSet('notStandardTableStash', JSON.stringify(stash_data));
    },

    // 初始化表格宽度函数
    buildColumn() {
      try {
        let stash_data = storageGet('notStandardTableStash');
        stash_data = stash_data && JSON.parse(stash_data);
        let pageStash = stash_data[`${this.tableStashKey}`] || {};
        this.$set(this, 'tableListForWidthStash', { ...this.tableListForWidthStash, ...pageStash });
      } catch (error) {
        console.warn(error, 'error try catch');
      }

    },
    // 导出账号
    async exportAccount(type) {
      if (!type && !this.multipleSelection.length)
        return this.$platform.alert('请至少选择一个用户！');
      export_state = type;
      let isContinue = true
      if(isContinue){
        if (export_state === 'all') {
          // 导出全部
          window.location.href = !this.selectedRole.id
            ? '/security/user/role/exportBatch?type=0'
            : `/security/user/role/exportBatch?roleId=${this.selectedRole.id}&type=0`;
        } else {
          // 导出选中的
          let ids = [];
          for (const user of this.multipleSelection) {
            ids.push(user.userId);
          }
          // ids = ids.join(',');
          const params = {
            userIdList: ids
          }
          let date = formatDate(safeNewDate(), 'YYYY-MM-DD');
          let fileName = `${date}${this.$t('department.tips.memberMessage')}.xlsx`;
          this.$http.post('/security/user/role/exportBatch/new', params, true, {responseType: 'blob'})
            .then(blob => {
              let link = document.createElement('a');
              let url = URL.createObjectURL(blob);
              link.download = fileName;
              link.href = url;
              this.$refs.bridge.appendChild(link);
              link.click();
              setTimeout(() => {
                URL.revokeObjectURL(url);
                this.$refs.bridge.removeChild(link);
              }, 150);
            })
            .catch(err => console.error(err));
          // window.location.href = `/security/user/role/exportBatch/new?userIdsStr=${ids}&type=0`;
        }
        export_state = '';
      }
    },
    async actionMany(type){
      if (this.multipleSelection.length <= 0) {
        return this.$platform.alert(`请先选择需要${ type == 'enable' ? '启用' : '禁用' }的成员`);
      }
      if (await this.$platform.confirm(`确定要把选中成员全部${ type == 'enable' ? '启用' : '禁用' }吗？`)) {
        this.userEnable(type);
      }
    },
    userEnable(type){
      let params = this.multipleSelection.map(item => item.userId)
      if(type == 'enable'){

        TeamApi.enableMany(params)
          .then(result => {
            let isSucc = result.status == 0;
            if (isSucc) {
              this.initialize(false);
            }
            this.$platform.notification({
              title: isSucc ? '成功' : '失败',
              message: isSucc ? '批量启用成功' : result.message,
              type: isSucc ? 'success' : 'error'
            });
          })
          .catch(err => console.log(err))
          .finally(() => (this.loading = false));
      }else{
        TeamApi.unableMany(params)
          .then(result => {
            let isSucc = result.status == 0;
            if (isSucc) {
              this.initialize(false);
            }
            this.$platform.notification({
              title: isSucc ? '成功' : '失败',
              message: isSucc ? '批量禁用成功' : result.message,
              type: isSucc ? 'success' : 'error'
            });
          })
          .catch(err => console.log(err))
          .finally(() => (this.loading = false));
      }
    },
    selectionToggle(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    // 导出动态
    exportFeed(type) {
      if (!type && !this.multipleSelection.length)
        return this.$platform.alert('请至少选择一个用户！');
      export_state = type;
      this.exportDialogvisible = true;
    },
    exportData() {
      let api = this.activeTypes.length > 0 ? '/security/user/taskRecord/exportBatch' : '/security/user/workState/exportBatch/new'
      let types = this.activeTypes.join(',');
      const [timeStart = '', timeEnd = ''] = this.selectdatetime || []
      const params = {
        [types ? 'createTimeStart' : 'timeStart']: timeStart,
        [types ? 'createTimeEnd' : 'timeEnd']: timeEnd,
        searchByTypesStr: types,
      }
      if (export_state === 'all') {
        // 导出全部
        params.roleId = this.selectedRole?.id
        window.location.href = `${api}?${objectToUrlParams(params)}`
      } else {
        // 导出选中的
        params.userIdsStr = (this.multipleSelection || []).map(item => item.userId).join(',')
        let date = formatDate(safeNewDate(), 'YYYY-MM-DD');
        let fileName = `${date}${this.$t('department.tips.memberMessage')}.xlsx`;
        this.$http.post(api, params, true, {responseType: 'blob'})
          .then(blob => {
            let link = document.createElement('a');
            let url = URL.createObjectURL(blob);
            link.download = fileName;
            link.href = url;
            this.$refs.bridge.appendChild(link);
            link.click();
            setTimeout(() => {
              URL.revokeObjectURL(url);
              this.$refs.bridge.removeChild(link);
            }, 150);
          })
          .catch(err => console.error(err));
      }
      export_state = '';
      this.selectionToggle();
      this.exportDialogClosed();
    },
    exportDialogClosed() {
      this.selectdatetime = [];
      this.exportDialogvisible = false;
    },

    /**
     * @des 获取列表当前的可滚动高度
     */
		 knowTableContainerHeight(){
      let min = 440;
      let delMin = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        // selection = selection ? selection + 8 : selection;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1  - 20 - 10;
        delMin =  window_ - 20 - 64 - 56 ;
        console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        console.log(min, 'min')
        min = min > 440 ? min : 440;
        delMin = delMin > 440 ? delMin : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'delTableContainerHeight', `${delMin}px`)
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    }
  },

  components: {
    [CreateUserPanel.name]: CreateUserPanel,
    [TeamEditView.name]: TeamEditView,
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
  },
};
</script>

<style lang="scss">
.el-form-item--small.el-form-item {
  margin-bottom: 16px;
}
.department-detail-header-title-box.department-detail-header-title span {
  margin-right: 0;
  font-weight: normal;
}
.el-tabs__header {
  margin-left: -1px;
  margin: 0;
}
.el-tabs__content {
  min-width: 300px;
  overflow-x: hidden;
  overflow-y: auto;
}

.collapse {
  span {
    padding: 5px;
    cursor: pointer;
    color: #666;
  }
  div {
    height: 53px;
    border-top: none;
    i.iconfont.icon-mianbanjiantou {
      font-size: 18px;
    }
  }
}

.el-tabs-expand {
  width: 400px;
}

.dept-search {
  display: flex;
  align-items: center;
  width: 100%;
  align-content: center;
  padding-bottom: 5px;
  .el-input {
    margin: 0 20px;
  }
  .dept-add {
    color: $color-primary-light-6;
    font-size: 30px;
    margin-right: 20px;
    cursor: pointer;
  }
}

.dept-search-border {
  // border-top: solid 1px #d9d9d9;
  padding-top: 10px;
}

.dept-header-see {
  margin-top: 20px;
  margin-left: 10px;
}
.dept-role-item {
  &:hover,
  &.department-role-selected {
    background-color: $color-primary-hover !important;
    color: $color-primary;
  }
}
.dept-del-role-item {
  flex: 1;
  position: absolute;
  bottom: 0;
  width: 100%;
  margin-top: 10px;
  border-top: 1px solid #eee;
}

.text-center {
  display: block;
  text-align: center;
  color: $color-primary-light-6;
}
.create-role {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  margin-right: 10px;
}

.dept-search-group {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 16px 0;
  .dept-search-group-left {
    display: flex;
    align-items: center;
    input {
      height: 34px;
      line-height: 34px;
    }
    button {
      margin-right: 8px;
    }
    .advanced-search-btn {
      margin-right: 12px;
      @include fontColor;
    }
  }
  .el-dropdown {
    padding: 4px 15px;
    margin-left: 8px;
    font-size: 14px;
    border-radius: 4px;
    outline: none;
    line-height: 24px;
    cursor: pointer;
  }
}

.department-main-right {
  .margin-top-0 {
    margin-top: 0;
  }
}
.department-user-header-total-top {
  display: flex;
  justify-content: space-between;
  line-height: 55px;
  border-bottom: 1px solid #e8e8e8;
  .title {
    font-size: 20px;
    color: #262626;
  }
  .surplus {
    color: #ff4d4f;
  }
  .margin-letft-24 {
    margin-left: 24px;
  }
  span {
    color: #595959;
  }
}
.department-user-header-total-bottom {
  line-height: 40px;
  margin-bottom: 12px;
  color: #595959;
}

.dept-edit-del {
  button {
    padding: 4px 15px;
    margin-left: 8px;
  }
}
.super-admin-label {
  background: rgba(255, 146, 0, 0.16);
  border-radius: 4px;
  border: 1px solid rgba(255, 146, 0, 0.16);
  color: #ff9200;
  padding: 0px 10px;
  font-size: 10px;
  display: inline-block;
  height: 24px;
  line-height: 24px;
  margin: 8px 5px;
}
.super-admin-label-auto {
  background: $color-primary-light-1;
  border: 1px solid $color-primary-light-1;
  color: $color-primary-light-6;
}

.reset-dialog-form {
  label {
    margin-bottom: 20px;
  }
}

html,
body,
.department-container {
  height: 100%;
}
body {
  padding: 10px;
  min-width: 1100px;
  overflow-x: auto;
}

.department-container {
  background: #edf0f5;
  border-radius: 3px;
  box-shadow: 0 1px 4px rgba(216, 216, 216, 0.65);

  display: flex;
  flex-flow: column nowrap;
}

.department-main {
  display: flex;
  flex-flow: row nowrap;
  flex: 1;

  height: 100%;
  position: relative;
}

.department-main-left {
  display: flex;
  flex: 2;
  flex-flow: column nowrap;

  min-width: 300px;

  .bc-dept {
    width: 100%;
    margin-top: 12px;
  }

  .base-tree-node-content {
    line-height: 32px;
  }

  .base-tree-node-arrow {
    width: 35px;
  }
}

.department-main-right {
  background: #edf0f5;
  border-radius: 2px;
  flex: 1;
  height: 100%;
  min-width: 400px;
  overflow-y: auto;
}

.department-tree-view {
  flex: 1;
  padding-top: 5px;
  overflow-y: auto;
}

.department-detail-header {
  border-radius: 4px;
  padding: 16px;
  background: #fff;
  &-title {
    display: flex;
    justify-content: space-between;
    line-height: 34px;

    span {
      font-size: 18px;
      font-weight: bold;

      margin-right: 30px;
    }
  }
}

.department-child-block {
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;

  &-header {
    margin-bottom: 10px;
  }
}
.department-main-right_bgFFF.department-main-right {
  .department-user-block {
    padding: 0 10px 0 10px;
    border-radius: 4px;
    background: #fff;
  }
}
.department-child-block,
.department-user-block {
  &-header {
    display: flex;
    justify-content: space-between;

    &-text {
      i {
        font-size: 20px;
      }
      span {
        font-size: 18px;
        font-weight: bold;
      }
    }

    &-btn {
    }
  }
}

.active-btn {
  cursor: pointer;
  color: rgb(15, 118, 139);
}

.department-user-table {
  .view-detail-btn {
    color: $color-primary-light-6;
    display: inline-block;
    min-width: 52px;
    // max-width: 140px;
    @include text-ellipsis();
  }
  .icon-people {
    font-size: 14px;
  }
  .table-footer {
    display: flex;
    justify-content: space-between;

    padding: 10px;

    background: #fff;
    border-radius: 0 0 3px 3px;

    .list-info {
      font-size: 13px;
      line-height: 32px;
      margin: 0;
      color: #767e89;
    }
    .el-pagination {
      white-space: nowrap;
      padding: 2px 5px;
      color: #303133;
      font-weight: bold;
    }
    .selectedCount {
      color: $color-primary;
      padding: 0 3px;
      width: 15px;
      text-align: center;
    }
    .select-init-text:hover {
      cursor: pointer;
    }
  }
}

.no-data-block {
  line-height: 30px;
  margin-top: 10px;
  text-align: center;
  color: #595959;
  font-size: 14px;
  padding-bottom: 12px;
  .service-no-icon {
    display: block;
    height: 134px;
    margin: 32px auto 16px;
  }
}

.department-child-item {
  border-bottom: 1px solid #eee;
  cursor: pointer;

  display: flex;
  justify-content: space-between;

  background: #fff;
  line-height: 44px;
  padding: 0 20px;

  &:hover {
    background-color: #fafafa;
  }
}
.el-tabs.dept-tabs {
  margin-top: 12px;
  background: #fff;
  padding: 0 20px;
  border-radius: 4px;
}
.department-left {
  position: relative;
  background: #fff;
  border-radius: 4px;
  border-top-right-radius: 0;
  .el-button {
    margin: 14px 20px 0;
    width: 260px;
  }
  .sync-button {
    width: 360px;
  }
}
.department-state {
  .el-tabs__content {
    height: calc(100% - 100px);
  }
}
.base-modal-mask {
  z-index: 10000;
}
</style>
<style lang="scss" scoped>
.disable-popover, .transfer-btn {
  margin-left: 12px;
}
.disable-text {
  cursor: not-allowed;
  color: #c0c4cc !important;
}
.department-container {
  ::v-deep .v-step[data-v-7c9c03f0] {
    background: #fff !important;
    color: #333 !important;
    -webkit-filter: drop-shadow(
      0px 9px 28px 8px rgba(0, 0, 0, 0.05)
    ) !important;
    filter: drop-shadow(0px 9px 28px 8px rgba(0, 0, 0, 0.05)) !important;
    padding: 0 !important;
    min-width: 240px !important;
    max-width: 350px !important;
  }

  ::v-deep .v-step .v-step__arrow[data-v-7c9c03f0] {
    border-color: #fff;
    border-left-color: transparent !important;
    border-right-color: transparent !important;
  }

  .tour-content-box {
    position: relative;
    overflow: hidden;
    padding: 0 20px;
    border-radius: 4px;

    .tour-left-tips {
      width: 80px;
      height: 32px;
      background: $color-primary;
      color: #fff;
      position: absolute;
      left: -40px;
      top: 0px;
      line-height: 40px;
      font-size: 12px;
      transform-origin: center top;
      transform: rotateZ(-45deg);
      text-align: center;
    }

    .tour-content {
      .tour-content-head {
        padding-top: 32px;
        padding-bottom: 10px;

        .iconfont {
          font-size: 10px;
          margin-bottom: 2px;
          color: #999;
          cursor: pointer;
        }
      }

      .tour-content-con {
        text-align: start;
        padding-bottom: 12px;
        color: #666;
      }
    }
  }

  .tour-bottom {
    height: 52px;
    padding: 0 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .btns {
      width: 60px;
      height: 28px;
      background: $color-primary;
      color: #fff;
      text-align: center;
      line-height: 28px;
      border-radius: 4px;
    }

    .text {
      color: $color-primary;
    }

    :nth-child(n) {
      cursor: pointer;
    }

    :not(:last-child) {
      margin-right: 12px;
    }
  }

  /* 向上的箭头 */

  .normal-arrow-top {
    font-size: 0;
    line-height: 0;
    border-width: 0.5rem;
    border-color: #fff;
    width: 0;
    border-top-width: 0;
    border-style: dashed;
    border-bottom-style: solid;
    border-left-color: transparent;
    border-right-color: transparent;
    position: absolute;
    top: -0.5rem;
  }

  .guide-model-box {
    position: fixed;
    width: 100%;
    height: 100vh;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 996;
  }

  .guide-point {
    z-index: 997;
    position: sticky;
  }

  .bg-w {
    background: #fff;
  }

  .dept-step-1-box {
    position: absolute;
    top: 0;
    z-index: 997;
  }
}
.form-view-row-content-address {
  cursor: pointer;
}
.form-view-row-content-address:hover {
  color: $color-primary-light-6;
}
.dept-title {
  color: $color-primary-light-6;
  height: 35px;
  box-sizing: border-box;
  line-height: 40px;
  font-size: 14px;
  font-weight: 500;
  text-align: center;
  margin-top: 10px;
}
.dept-info {
  margin-bottom: 12px;
  width: 80%;
  label {
    display: block;
    width: 100%;
  }
  .form-view-row {
    display: block;
    padding: 0;
    padding-right: 24px;
    box-sizing: border-box;
    span.count {
      font-size: 26px;
      line-height: 40px;
    }
  }
}
.department-detail-header-title {
  font-size: 16px;
}
</style>

<style lang="scss">
.reset-dialog-form-dialog {
  .el-dialog__body {
    padding-bottom: 50px;
  }
}
</style>